<?php

namespace App\Http\Services;

use App\Http\Repositories\Daos\Order\OrderDao;
use App\Http\Repositories\Redis\CacheDataRedis;
use App\Http\Requests\UserContext;
use App\Http\Traits\Errors;
use App\Http\Traits\GlobalConstant;
use App\Models\Article;
use App\Models\Drag;
use App\Models\DragDetail;
use App\Models\DragonView;
use App\Models\Order;
use App\Util\Helper;
use EasyWeChat\Factory;
use Intervention\Image\Facades\Image;

class PlatformService extends BaseService
{
    use Errors;

    public function resourceList()
    {
        $basic = CacheDataRedis::getRedisInstance()->systemConfig('basic') ?? [];
        $rule  = CacheDataRedis::getRedisInstance()->systemConfig('rule') ?? [];
        return compact("basic", "rule");
    }

    public function articleDetail()
    {
        $id = request('article_id') ?? 0;
        return Article::find($id);
    }


    public function wechatMessageList()
    {
        $type = request('type') ?? '';
        if (empty($type)) {
            return [];
        }
        switch ($type) {
            case 'bm':
                $arr = [
                    'U5BdigRmMI4dRoZSg9sh5pryRYHbeCK-G-HRiuBbjFM',//预约成功订阅消息
                    'HtCd3_f2R2EUBeffKXm_c9YsUz0yg49E-iwA3s1l3Zw',//日程提醒
                ];
                break;
            default:
                $arr = [];
                break;
        }
        return $arr;
    }

    public function helpList()
    {
        return Article::where('article_cat_id', 1)->where('status', 1)->get();
    }

    public function helpDetail()
    {
        $id = request('id') ?? 0;
        return Article::where('id', $id)->where('status', 1)->first();
    }

    public function dragonView(UserContext $userContext)
    {
        $userId   = $userContext->getId();
        $dragonId = request('dragon_id') ?? 0;
        if (empty($userId)) {
            return true;
        }
        $detail = DragonView::where('dragon_id', $dragonId)->where('user_id', $userId)->first();
        if (empty($detail)) {
            DragonView::create(['dragon_id' => $dragonId, 'user_id' => $userId]);
            return true;
        }
        return true;
    }

    protected static function shareCard1($dragonId, $textContent, $firstPrice, $firstPic)
    {
        $goodsImg = self::resizeImage([$firstPic], 250, 250, 'goods-250-card');
        $oldImage = Image::make('uploads/bg.png');
        $oldImage->insert($goodsImg, 'top-left', 20, 20);
        //添加文字
        $textLength = mb_strlen($textContent);
        $offset     = 0;
        if ($textLength <= 7) {
            $oldImage->text($textContent, 300, 60, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(26);
                $font->color('#000000');
            });
        } else {
            $page = $textLength > 21 ? 4 : intval(ceil($textLength / 7));
            for ($i = 0; $i < $page; $i++) {
                $offset++;
                $str = mb_substr($textContent, $i * 7, 7);
                if ($textLength > 21 && $i == $page - 1) {
                    $str = mb_substr($str, 0, 5) . '...';
                }
                $oldImage->text($str, 300, 60 + $i * 30, function ($font) {
                    $font->file(public_path('PingFang Regular.ttf'));
                    $font->size(26);
                    $font->color('#000000');
                });
            }
        }
        $oldImage->text("￥$firstPrice", 300, 200, function ($font) {
            $font->file(public_path('PingFang Bold.ttf'));
            $font->size(36);
            $font->color('#FF0000');
        });
        $oldImage->insert('uploads/btn1.png', '', 300, 220);
        $orderService = new OrderService(new OrderDao(new Order()));
        $orderList    = $orderService->serial($dragonId, 2)->toArray();
        for ($i = 0; $i < count($orderList); $i++) {
            $info = $orderList[$i];
            $oldImage->text($info['dragon_serial'], 40, 340 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#000000');
            });
            $tempImage = self::createCircleImage($info['user_info']['avatar'], 30, $info['user_info']['id']);
            $oldImage->insert($tempImage, 'top-left', 60, 316 + $i * 40);
            $strLen       = mb_strlen($info['first_title']);
            $thirdContent = $strLen > 7 ? mb_substr($info['first_title'], 0, 7) . '...' : $info['first_title'];
            $fourContent  = '+' . $info['total_num'];
            $oldImage->text($info['nickname'], 100, 340 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#000000');
            });
            $oldImage->text($info['time_str'], 160, 340 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#999999');
            });
            $oldImage->text($thirdContent, 260, 340 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#000000');
            });
            $oldImage->text($fourContent, 450, 340 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#000000');
            });
        }
        ob_end_clean();
        $return = 'uploads/card/card' . $dragonId . '-1.png';
        $path   = 'card/card' . $dragonId . '-1.png';
        $oldImage->save($return);
        $default_disk = config('admin.upload.disk');
        return config('filesystems.disks.' . $default_disk . '.url') . $path;
    }

    protected static function resizeImage($picArr, $width, $height, $type)
    {
        $returnArr = [];
        for ($i = 0; $i < count($picArr); $i++) {
            $pic       = $picArr[$i];
            $temp      = explode('/', $pic);
            $tempImage = Image::make('uploads/avatar/' . $temp[5]);
            $tempImage->resize($width, $height);
            $file        = explode('.', $temp[5]);
            $return_name = 'uploads/card/' . $type . $file[0] . '-' . ($i + 1) . '.' . $file[1];
            $returnArr[] = $return_name;
            $tempImage->save($return_name, 60);
        }
        if (count($picArr) > 1) {
            return $returnArr;
        }
        return $returnArr[0];
    }

    protected static function shareCard2($dragonId, $priceArr, $goodsImg)
    {
        $oldImage = Image::make('uploads/bg.png');
        $priceEnd = $priceArr[count($priceArr) - 1];
        $oldImage->text("￥$priceArr[0]~$priceEnd", 20, 60, function ($font) {
            $font->file(public_path('PingFang Bold.ttf'));
            $font->size(36);
            $font->color('#FF0000');
        });
        $imgList = self::resizeImage($goodsImg, 150, 150, 'goods-150-card');
        if (is_array($imgList)) {
            for ($i = 0; $i < count($imgList); $i++) {
                $oldImage->insert($imgList[$i], 'top-left', 20 + 155 * $i, 80);
            }
        } else {
            $oldImage->insert($imgList, 'top-left', 20, 80);
        }
        $orderService = new OrderService(new OrderDao(new Order()));
        $orderList    = $orderService->serial($dragonId, 2)->toArray();
        $offset       = 0;
        for ($i = 0; $i < count($orderList); $i++) {
            $offset++;
            $info = $orderList[$i];
            $oldImage->text($info['dragon_serial'], 20, 280 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#000000');
            });
            $tempImage = self::createCircleImage($info['user_info']['avatar'], 30, $info['user_info']['id']);
            $oldImage->insert($tempImage, 'top-left', 40, 256 + $i * 40);
            $strLen       = mb_strlen($info['first_title']);
            $thirdContent = $strLen > 7 ? mb_substr($info['first_title'], 0, 7) . '...' : $info['first_title'];
            $fourContent  = '+' . $info['total_num'];
            $oldImage->text($info['nickname'], 80, 280 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#000000');
            });
            $oldImage->text($info['time_str'], 140, 280 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#999999');
            });
            $oldImage->text($thirdContent, 235, 280 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#000000');
            });
            $oldImage->text($fourContent, 430, 280 + $i * 40, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(24);
                $font->color('#000000');
            });
        }
        $oldImage->insert('uploads/btn2.png', 'top-left', 30, $offset * 20 + 290);
        $return = 'uploads/card/card' . $dragonId . '-2.png';
        $path   = 'card/card' . $dragonId . '-2.png';
        $oldImage->save($return);
        $default_disk = config('admin.upload.disk');
        return config('filesystems.disks.' . $default_disk . '.url') . $path;
    }

    protected static function shareCard($dragonId, $goodsImg)
    {
        $oldImage = Image::canvas(500, 400, '#FFFFFF');
        $imgList  = self::resizeImage([$goodsImg], 500, 400, 'goods-450-card');
        $oldImage->insert($imgList, 'top-left', 1, 1);
        $return = 'uploads/card/card' . $dragonId . '-3.png';
        $path   = 'card/card' . $dragonId . '-3.png';
        $oldImage->save($return);
        $default_disk = config('admin.upload.disk');
        return config('filesystems.disks.' . $default_disk . '.url') . $path;
    }

    public function createShareCard()
    {
        $dragonId   = request('dragon_id') ?? 0;
        $dragonInfo = Drag::where('id', $dragonId)->first(['id', 'title', 'user_id']);
        if (empty($dragonInfo)) $this->showError('创建分享数据异常');
        $list = DragDetail::where('drag_id', $dragonId)->get(['id', 'drag_id', 'title', 'price', 'pics'])->toArray();
        if (empty($list)) $this->showError('分享商品异常');
        $picList  = [];
        $priceArr = array_column(GlobalConstant::sortGoodsPrice($list), 'price');
        foreach ($list as $item) {
            foreach ($item['pics'] as $value) {
                if ($value['type'] == 1) {
                    $picList[] = $value['src'];
                    break;
                }
            }
        }
        $share_list[] = ['title' => $dragonInfo['title'] . '  ' . GlobalConstant::formatNumber($list[0]['price']) . '/件', 'dragon_id' => $dragonId, 'user_id' => $dragonInfo['user_id'], 'share_img' => self::shareCard($dragonId, $picList[0])];
        $share_list[] = ['title' => $dragonInfo['title'], 'dragon_id' => $dragonId, 'user_id' => $dragonInfo['user_id'], 'share_img' => self::shareCard1($dragonId, $dragonInfo['title'], GlobalConstant::formatNumber($list[0]['price']), $picList[0])];
        $share_list[] = ['title' => $dragonInfo['title'], 'dragon_id' => $dragonId, 'user_id' => $dragonInfo['user_id'], 'share_img' => self::shareCard2($dragonId, $priceArr, $picList)];
        return $share_list;
    }

    public function createSharePoster()
    {
        $dragonId  = request('dragon_id') ?? 0;
        $dragInfo  = Drag::where('id', $dragonId)->with("publishUserInfo")->first();
        $image     = Image::make('uploads/poster_bg.png');
        $tempImage = self::createCircleImage($dragInfo['publishUserInfo']['avatar'], 90, $dragInfo['publishUserInfo']['id']);
        $image->insert($tempImage, 'top-left', 80, 54);
        $image->text($dragInfo['publishUserInfo']['nickname'], 200, 116, function ($font) {
            $font->file(public_path('PingFang Bold.ttf'));
            $font->size(36);
            $font->color('#000000');
        });
        $image->text($dragInfo['title'], 80, 220, function ($font) {
            $font->file(public_path('PingFang Bold.ttf'));
            $font->size(36);
            $font->color('#000000');
        });
        $textContent = $dragInfo['description'];
        $textLength  = mb_strlen($textContent);
        $offset      = 0;
        if ($textLength <= 16) {
            $image->text($textContent, 80, 280, function ($font) {
                $font->file(public_path('PingFang Regular.ttf'));
                $font->size(36);
                $font->color('#666666');
            });
        } else {
            $page = intval(ceil($textLength / 16));
            for ($i = 0; $i < 2; $i++) {
                $offset++;
                $str = mb_substr($textContent, $i * 16, 16);
                if ($page > 2 && $i == 1) {
                    $str = mb_substr($textContent, 16, 16) . '...';
                }
                $image->text($str, 80, 280 + $i * 46, function ($font) {
                    $font->file(public_path('PingFang Regular.ttf'));
                    $font->size(36);
                    $font->color('#666666');
                });
            }
        }
        $list     = DragDetail::where('drag_id', $dragonId)->get(['id', 'drag_id', 'title', 'price', 'pics'])->toArray();
        $priceArr = array_column(GlobalConstant::sortGoodsPrice($list), 'price');
        $priceEnd = $priceArr[count($priceArr) - 1];
        $image->text("￥$priceArr[0]~$priceEnd", 80, 420, function ($font) {
            $font->file(public_path('PingFang Bold.ttf'));
            $font->size(50);
            $font->color('#FF0000');
        });
        $timeStr = Helper::pastTime($dragInfo['created_at']);
        $image->text($timeStr . '发布', 500, 420, function ($font) {
            $font->file(public_path('PingFang Bold.ttf'));
            $font->size(32);
            $font->color('#999999');
        });
        $picList = [];
        foreach ($list as $item) {
            foreach ($item['pics'] as $value) {
                if ($value['type'] == 1) {
                    $picList[] = $value['src'];
                    break;
                }
            }
        }
        $imgList = self::resizeImage($picList, 200, 200, 'goods-200-card');
        if (is_array($imgList)) {
            for ($i = 0; $i < count($imgList); $i++) {
                $image->insert($imgList[$i], 'top-left', 80 + 205 * $i, 460);
            }
        } else {
            $image->insert($imgList, 'top-left', 80, 460);
        }
//        $image->insert('uploads/qrcode.png', 'top-left', 315, 700);//之前是固定的小程序码
        $image->insert(self::getQrcode($dragonId, $dragInfo['user_id']), 'top-left', 315, 700);
        $image->insert('uploads/person.png', 'top-left', 215, 880);
        $return = 'uploads/card/card' . $dragonId . '-poster.png';
        $path   = 'card/card' . $dragonId . '-poster.png';
        $image->save($return);
        $default_disk = config('admin.upload.disk');
        return config('filesystems.disks.' . $default_disk . '.url') . $path;
    }

    protected static function createCircleImage($imageUrl, $size, $userId)
    {
        $src_img = imagecreatefromstring(file_get_contents($imageUrl));

        list($w, $h) = getimagesize($imageUrl);
        $w   = $h = min($w, $h);
        $img = imagecreatetruecolor($w, $h);
        imagesavealpha($img, true);

        // 拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);

        imagefill($img, 0, 0, $bg);
        $r = $w / 2; // 圆的半径
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r)))
                    imagesetpixel($img, $x, $y, $rgbColor);
            }
        }
        imagedestroy($src_img);
        $image = Image::make($img);
        $image->resize($size, $size);
        $return = 'uploads/avatar/' . $userId . '_' . $size . '.png';
        $image->save($return, 60);
//        return $img;
        return $return;
    }

    protected static function getQrcode($dragonId, $leaderId)
    {
        $cacheKey = 'wechat_access_token';
        $token    = CacheDataRedis::getRedisInstance()->get($cacheKey);
        if (empty($token)) {
            $app   = Factory::miniProgram(config('wechat.mini_program.default'));
            $data  = $app->access_token->getToken();
            $token = $data['access_token'];
            CacheDataRedis::getRedisInstance()->set($cacheKey, $token, 7200);
        }
        $buffer = Helper::http_mini_curl('https://api.weixin.qq.com/wxa/getwxacode?access_token=' . $token, ['path' => '/pages/record/detail?id=' . $dragonId . '&leader_id=' . $leaderId, 'width' => 152, 'env_version' => config('app.mini_version')], true);
        $image  = Image::make($buffer);
        $image->resize(152, 152);
        $return = 'uploads/qrcode/' . $dragonId . '.png';
        $image->save($return, 60);
        return $return;
    }

}
